package config;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import javax.sql.DataSource;
import org.apache.ibatis.datasource.pooled.PooledDataSource;
import org.apache.ibatis.io.Resources;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;

@Configuration
@Order(1)
public class DataSourseConfiguration {

    private static DataSourseConf toDataSourseConf(Properties p) {
        return new DataSourseConf(p.getProperty("db.driver"),
            p.getProperty("db.url"),
            p.getProperty("db.usernam"),
            p.getProperty("db.password"));
    }

    @Bean
    public static DataSourseConf dataSourseConf() {
        String path = "resources/db.properties";
        Properties props = new Properties();
        InputStream in = null;
        try {
            in = Resources.getResourceAsStream(path);
            props.load(in);
            in.close();
            return toDataSourseConf(props);
        } catch (IOException e) {
        } finally {
            try {
                in.close();
            } catch (IOException e) {
            }
        }
        return null;
    }

    @Bean
    public static DataSource dataSource(DataSourseConf dataSourseConf) {
        return new PooledDataSource(dataSourseConf.getDriver(),
            dataSourseConf.getUrl(),
            dataSourseConf.getUsernam(),
            dataSourseConf.getPassword());
    }
}
